# -*- coding: utf-8 -*-
# vim: set noet ts=4:
#
# scim-python
#
# Copyright (c) 2007-2008 Yu Fan <yufanyufan@gmail.com>
#
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330,
# Boston, MA  02111-1307  USA
#
# $Id: $
#
from ZhengJu import *
import scim
import os
from scim import KeyCode
from scim import KeyMask
from scim import Property
import traceback
import sys
from PYDict import *
from gettext import dgettext

_ = lambda a : dgettext ("scim-python", a)
class ShuangPinEngine (Engine):

	def __init__ (self, factory, config, encoding, id):
		Engine.__init__(self, factory, config, encoding, id)

	def reload_config(self,config):
		self.reset()
		self.schema = config.read ("/IMEngine/Python/ZhengJu/ShuangPinSchema", "MSPY")
		#~ print self.schema
		if not self.schema in SHUANGPIN_SCHEMAS.keys ():
			self.schima = "MSPY"
		(self.shengmu_schema, self.yunmu_schema) = SHUANGPIN_SCHEMAS[self.schema]
		Engine.reload_config(self,config)
		
	def translate(self,key):
		if(self._editor.current () == None or self._editor.current ().is_complete ()):
			if unichr (key.code) in self.shengmu_schema:
				self._editor.pinyinlist.append (PinYinWord(self.shengmu_schema[unichr (key.code)],""))
				if not self.progresivepromp:
					return
			else:
				raise InputException
		else:
			if unichr(key.code) in self.yunmu_schema:
				yunmu = self.yunmu_schema[unichr(key.code)]
				p = None
				for i in yunmu:
					pinyin = self._editor.current ().get_shengmu () + i
					if pinyin in PINYIN_LIST:
						p = i
						break
				if p == None:
					raise InputException ()
				self._editor.current().set_yunmu (p)
			else:
				raise InputException
		self._editor.auto_convert ()		
	def chinese_process_key_event (self, key):
		if (self.schema=="MSPY" or self.schema=="ZGPY") and key.mask == KeyMask.NullMask and (\
			(key.code >= KeyCode.KEY_a and key.code <= KeyCode.KEY_z) or \
			key.code == KeyCode.KEY_semicolon):
			self.translate(key)
			return True
		elif key.mask == KeyMask.NullMask \
			and (key.code >= KeyCode.KEY_a and key.code <= KeyCode.KEY_z):
			self.translate(key)
			return True
		elif self._editor.pinyinlist and key.code == KeyCode.KEY_BackSpace:
			if self._editor.pinyinlist[-1].is_complete ():
				self._editor.pinyinlist[-1].set_yunmu ("")
				if not self.progresivepromp:
					return True
			else:
				del self._editor.pinyinlist[-1]
			self._editor.update ()
			return True
		elif Engine.chinese_process_key_event (self,key):
			return True;
		return False

class ShuangPinFactory (IMEngineFactory):
	def __init__ (self, config):
		IMEngineFactory.__init__ (self, config)
		self.name 		= _(u"ShuangPin")
		self.uuid 		= "5d2ceb47-7567-4d74-980f-26d5d300ea66"
		self.authors	= u"Yu Fan <yufanyufan@gmail.com>"
		self.icon_file 	= "/usr/share/scim/icons/scim-python.png"
		self.credits 	= u"GPL"
		self.help		= _(u"Help For ShuangPin")
		self.set_languages ("zh")
		self._config	= config
	def create_instance (self, encoding, id):
		engine =  ShuangPinEngine (self, self._config, encoding, id)
		return engine

	def reload_config (self, config):
		pass


def test_add_char(editor, char):
	if(editor.current () == None or editor.current ().is_complete ()):
		editor.pinyinlist.append(PinYinWord(MSPY_SHUANGPIN_SHENGMU_DICT[char],""))
	else:
		yunmu = MSPY_SHUANGPIN_YUNMU_DICT[char]
		p = None
		for i in yunmu:
			pinyin = editor.current ().get_shengmu() + i
			if pinyin in PINYIN_LIST:
				p = i
				break
		if p == None:
			raise Exception ()
		editor.current ().set_yunmu (p)
	editor.auto_convert ()

def test_case(pinyin,modify = None, sentence=None):
	editor = Editor ()
	editor.schema = "MSPY"
	editor.userword = False
	editor.userphrase = False
	editor.adjustfreq = False
	
	(editor.shengmu_schema, editor.yunmu_schema) = SHUANGPIN_SCHEMAS [editor.schema]
	for i in pinyin:
		test_add_char (editor,i)
	editor.convert_all ()
	if modify:
		for i in range (0,len(modify)):
			editor.wordlist[i].char=modify[i]
	result = editor.commit ()
	print result
	if sentence:
		assert editor.commit () == sentence

def test():
	test_case("fhdiijklfauhdedstmjqykllle")
	test_case("woxihr")
	test_case("hvbuhvybufme")
	test_case("zfmehvuioa")
	test_case("kklydkde")
	test_case("devild")
	test_case("veybvuyu")

if __name__ == "__main__":
	import timeit
	t = timeit.Timer("ShuangPin.test()","import ShuangPin")
	print t.repeat(1,1)
